<?php
/**
 * Created by PhpStorm.
 * User: joe
 * Date: 17-11-5
 * Time: 下午7:07
 */

namespace App\Controllers;

use \App\App;

class Index extends App
{
    public function __construct()
    {
        parent::__construct();
        $this->language->load('app/home');
    }

    public function index()
    {
        $categoryModel = new \App\Models\Category();
        $noticeModel = new \App\Models\Notice();
        $statModel = new \App\Models\Stat();
        $this->view->categories = $categoryModel->where(['parent' => 0])->findAll();
        $this->view->notices = $noticeModel->order("date", "DESC")->findAll(5);
        $this->view->hots = $this->getHots(null, 3, "favorites");
        //$this->view->clicks = $this->getHots(null, 20, "click");
        //$this->view->last = $this->getHots(null, 20, "last_update");
        //统计流量
        $visit = cookie("visit");
        if (!$visit) {
            $stat = $statModel->where('date', date("Y-m-d"))->first();
            if ($stat) {
                $stat['visit']++;
            } else {
                $stat = [
                    'date' => date("Y-m-d"),
                    'visit' => 1,
                    'story' => 0,
                    'download' => 0,
                ];
            }
            $statModel->save($stat);

            cookie("visit", true);
        }
        $this->render('/front/home', "/front/header");
    }

    public function getHots($cateid = null, $num = 5, $sort = "click")
    {
        $storyModel = new \App\Models\Story();
        if ($cateid) {
            $categoryModel = new \App\Models\Category();
            $category = $categoryModel->find($cateid);
            $storyModel->where("category", $category['name']);
        }
        $hots = $storyModel->order($sort, "DESC")->findAll($num);
        if ($this->request->isAjax()) {
            $this->showJson($hots);
        } else {
            return $hots;
        }
    }
}